#coding='utf-8'
from requests import Request, Session
import time
from imp import reload
from urllib import request as urllib2
from lxml import etree
import pymysql
import json
import sys
reload(sys)
import requests
#
def get_one_page(url):
    response = requests.get(url)
    response.encoding = "utf-8"
    if response.status_code == 200:
        return response.text
    return None

def main():
    db = pymysql.connect(host='localhost', user='root', password='', port=3306, db='nbaData', charset='utf8')
    cursor = db.cursor()
    insert_nbaTeam_sql = 'REPLACE INTO nbateam(team,href) VALUES (%s, %s)'
    nbaTeam_url = 'http://www.stat-nba.com/teamList.php'
    text = get_one_page(nbaTeam_url)
    dom = etree.HTML(text)
    if dom is None:
        return
    node_list = dom.xpath('//table[@class="stat_box"]/tr[3]')
    print(node_list)
    for node in node_list:
        nodelistTd = node.xpath('./td')
        for nodeTd in nodelistTd:
            nodeA = nodeTd.xpath('./div')
            for nodeB in nodeA:
                teamName = nodeB.xpath('./a/div/text()')
                teamHref = nodeB.xpath('./a/@href')[0].strip('.')
                cursor.execute(insert_nbaTeam_sql, (teamName,teamHref))
                db.commit()
if __name__ == '__main__':
    main()